package com.itheima.web.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.domain.User;
import com.itheima.domain.Result;
import com.itheima.factory.BeanFactory;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import com.itheima.utils.BeanUtil;
import com.itheima.utils.MD5Util;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/system/user/*")
public class UserServlet extends BaseServlet {
  private  UserService userService = BeanFactory.getService("userService", UserService.class);

    private Result findLoginUser(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {

            Object user = req.getSession().getAttribute("user");
            //3 响应结果到客户端
            return new Result(true,MessageConstant.QUERY_USER_SUCCESS,user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_USER_FAIL);
        }
    }

    private Result updateUserAndRoles(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            //1 获取请求参数 userId 和checkedRoleIds
            String userId = req.getParameter("userId");
            String[] checkedRoleIds = BeanUtil.fillBeanFromJson(req, String[].class);
            //2 调用service，根据用户绑定的角色也叫给用户授权
            userService.updateUserAndRoles(userId,checkedRoleIds);
            //3 响应结果到客户端
            return new Result(true,MessageConstant.SETTING_USER_AUTHORIZE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SETTING_USER_AUTHORIZE_FAIL);
        }
    }

        private Result findAll(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            //2 调用service层方法获取分页结果
            
            List<User> list= userService.findAll();
            //3 对客户的作出响应
           return new Result(true,MessageConstant.QUERY_USER_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
           return new Result(false,MessageConstant.QUERY_USER_FAIL);
        }
    }

    private Result delete(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            //1 获取请求参数并封装成User对象
            String[] ids = BeanUtil.fillBeanFromJson(req, String[].class);
            //2 调用service层方法添加数据
           
            userService.delete(ids);
            //3 响应结果
           return new Result(true,MessageConstant.DELETE_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
           return new Result(false,MessageConstant.DELETE_USER_FAIL);
        }
    }

    private Result edit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            //1 获取请求参数并封装成User对象
            User user = BeanUtil.fillBeanFromJson(req, User.class);
            //2 调用service层方法添加数据

            userService.update(user);
            //3 响应结果
           return new Result(true,MessageConstant.EDIT_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
           return new Result(false,MessageConstant.EDIT_USER_FAIL);
        }
    }

    private Result findById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            //1 获取请求参数
            String id = req.getParameter("id");
            //2 调用service层方法获取分页结果

            User user = userService.findById(id);
            //3 对客户的作出响应
           return new Result(true,MessageConstant.QUERY_USER_SUCCESS,user);
        } catch (Exception e) {
            e.printStackTrace();
           return new Result(false,MessageConstant.QUERY_USER_FAIL);
        }
    }

    private Result save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            //1 获取请求参数并封装成User对象
            User user = BeanUtil.fillBeanFromJson(req, User.class);
            String password = MD5Util.md5(user.getPassword());
            user.setPassword(password);
            //2 调用service层方法添加数据

            userService.save(user);
            //3 响应结果
           return new Result(true,MessageConstant.SAVE_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
           return new Result(false,MessageConstant.SAVE_USER_FAIL);
        }
    }

    /*
     * 处理分页查询的请求
     * @param request
     * @param response
     */
    private Result findByPage(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            //1 获取请求参数（当前页数和每页条数）
            String currentPage1 = req.getParameter("currentPage");
            String pageSize1 = req.getParameter("pageSize");
            //2.判断是否为空
            int currentPage = 1,pageSize = 5;
            if (!StringUtils.isBlank(currentPage1)){
                //3.给页码和条数赋默认值
                currentPage = Integer.parseInt(currentPage1);

            }
            if (!StringUtils.isBlank(pageSize1)){
                //3.给页码和条数赋默认值
                pageSize = Integer.parseInt(pageSize1);

            }
            //4.调用Service层方法获得结果

            PageInfo<User> page = userService.findByPage(currentPage, pageSize);
            //5.给客户端响应
           return new Result(true,MessageConstant.QUERY_COMPANY_SUCCESS,page);
        } catch (Exception e) {
            e.printStackTrace();
           return new Result(false,MessageConstant.QUERY_COMPANY_FAIL);
        }
    }

//    @Override
//    protected Result doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, Exception {
//        doGet(req, resp);
//    }
}
